package com.atguigu.ticket;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SellTicket {
    private int ticket=50;
    private final Lock lock = new ReentrantLock(); // 可重入锁
    public void sale(){
        lock.lock();
        try {
            if (ticket>0){
                System.out.println(Thread.currentThread().getName()+"...买了第"+ticket--+"张票,还剩"+ticket+"张票");
            }
        }finally {
            lock.unlock();
        }

    }


        public static void main(String[] args) {
            SellTicket sellTicket = new SellTicket();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i <= 50; i++) {
                        sellTicket.sale();
                    }
                }
            },"赵四").start();
           new  Thread(()->{for (int i = 0; i <= 50; i++) { sellTicket.sale();}},"李四").start();
           new  Thread(()->{for (int i = 0; i <= 50; i++) { sellTicket.sale();}},"王五").start();

    }
}
